package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> orderSettings) {
        if (orderSettings != null && orderSettings.size()>0){
            for (OrderSetting orderSetting : orderSettings) {
                // 判断，当前预约时间是否在数据库中存在记录
                updateOrAdd(orderSetting);
            }
        }
    }

    @Override
    public List<Map<String, Object>> getOrderSettingByMonth(String date) {
        // 传入的date的格式2019-12
        // 方案一：拼接1-31
        /*String begin = date+"-01";
        String end = date+"-31";
        Map<String,String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);*/

        //查询当前月份的预约设置
        //方案二：不拼接，直接使用模糊查询，
        // 但月份小于10时需要+0，已在前台代码添加，也可在后台自行添加(此时没有第一种方式简单)
        //List<OrderSetting> orderSettingList = orderSettingDao.getOrderSettingByMonth(date);

        // 组织查询结果的数据List<Map>
        /*List<Map<String, Object>> mapList = new ArrayList<>();
        if (orderSettingList !=null && orderSettingList.size()>0){
            for (OrderSetting orderSetting : orderSettingList) {
                Map<String,Object> hashMap = new HashMap<>();
                hashMap.put("date",orderSetting.getOrderDate().getDate());//获得日期（几号）
                hashMap.put("number",orderSetting.getNumber());
                hashMap.put("reservations",orderSetting.getReservations());
                mapList.add(hashMap);
            }
        }*/

        //方案三：直接封装到List<Map>中，在xml中使用模糊查询和date_format函数并设置别名
        //List<Map<String, Object>> mapList = orderSettingDao.getOrderSettingByMonth(date);

        return orderSettingDao.getOrderSettingByMonth(date);
    }

    @Override
    public void editNumberByOrderDate(OrderSetting orderSetting) {
        // 判断，当前预约时间是否在数据库中存在记录
        updateOrAdd(orderSetting);
    }

    private void updateOrAdd(OrderSetting orderSetting) {
        // 判断，当前预约时间是否在数据库中存在记录
        long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (count > 0){
            // 如果不存在记录，新增
            // 新增
            orderSettingDao.updateNumberByOrderDate(orderSetting);
        }else {
            // 如果存在记录，使用预约时间更新最多预约人数
            orderSettingDao.add(orderSetting);
        }
    }
}
